package com.janko.springbootbase.a_projectExample.poi;

import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFRelation;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;

import static com.janko.springbootbase.a_projectExample.poi.ExcelWaterRemarkUtils.createWaterMark;

/**
 * @Author nyk
 * @Date 2021/4/30 10:08
 * @Version 1.0
 * @Desc
 */
public class MyPOI {


    public static void main(String[] args) throws IOException {
        InputStream inputStream = new FileInputStream("D:\\demo.xlsx");
        XSSFWorkbook wb = (XSSFWorkbook) WorkbookFactory.create(inputStream);
        OutputStream out =null;
        for (int i = 0; i < wb.getNumberOfSheets(); i++) {
            XSSFSheet sheet =  wb.getSheetAt(i);
            try (ByteArrayOutputStream byteArrayOutputStream = createWaterMark("我是水印")){
                int pictureIdx = wb.addPicture(byteArrayOutputStream.toByteArray(), Workbook.PICTURE_TYPE_PNG);
                String rID = sheet.addRelation(null, XSSFRelation.IMAGES, (POIXMLDocumentPart) wb.getAllPictures().get(pictureIdx))
                        .getRelationship().getId();
                sheet.getCTWorksheet().addNewPicture().setId(rID);
            }
            sheet.protectSheet("secretPassword");

        }
        out = new FileOutputStream("d:/demo_readonly.xlsx");
        wb.write(out);
    }
}
